package com.itjiange.servlet;

import com.itjiange.utils.CustomConstants;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * 上传文件
 *
 * @author ItJiange
 * @date 2023/10/18
 */
@WebServlet("/upload-file")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        // 获取 Part 对象
        Part filePart = req.getPart("myfile");
        // 获取文件名 xxx.xxx
        String fileName = filePart.getSubmittedFileName();
        System.out.println("上传文件名称：" + fileName);

        // 上传文件的完整路径
        String uploadPath = CustomConstants.ROOT_PATH + File.separator + fileName;
        System.out.println("上传文件的完整路径：" + uploadPath);

        File file = new File(uploadPath);
        // 当文件父级目录不存在时，创建目录
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        filePart.write(uploadPath);
        String downloadLink = "<a href=\"/download-file?file=" + fileName + "\" >下载图片</a>";
        resp.getWriter().write("<h1>上传成功</h1>" + downloadLink);
    }
}
